package com.h2cloud.JUCTest.patten;

/**
 * @Package: com.h2cloud.JUCTest.patten
 * @ClassName: ProducerConsumer
 * @Author: h2cloud
 * @CreateTime: 2025/2/16 11:39
 * @Description:
 */

import java.util.concurrent.*;

public class ProducerConsumer {

	static class SharedQueue {
		private final BlockingQueue<Integer> queue;

		public SharedQueue(int capacity) {
			queue = new LinkedBlockingQueue<>(capacity);
		}

		public void produce(int number) throws InterruptedException {
			queue.put(number);  // 将数字放入队列
		}

		public Integer consume() throws InterruptedException {
			return queue.take();  // 从队列中取出一个数字
		}
	}

	// 生产者类
	static class Producer implements Runnable {
		private final SharedQueue sharedQueue;

		public Producer(SharedQueue sharedQueue) {
			this.sharedQueue = sharedQueue;
		}

		@Override
		public void run() {
			try {
				for (int i = 0; i < 100; i++) {  // 生产100个数字
					int number = (int) (Math.random() * 100);  // 生成一个乱序的数字
					System.out.println("生产者生成数字: " + number + " " + (number % 2 == 0 ? "是偶数" : "是奇数"));
					sharedQueue.produce(number);
					Thread.sleep(100);  // 暂停一会，模拟生产过程
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

	// 偶数消费者
	static class EvenConsumer implements Runnable {
		private final SharedQueue sharedQueue;

		public EvenConsumer(SharedQueue sharedQueue) {
			this.sharedQueue = sharedQueue;
		}

		@Override
		public void run() {
			try {
				while (true) {
					int number = sharedQueue.consume();
					if (number % 2 == 0) {
						System.out.println("偶数消费者消费偶数数字: " + number);
					} else {
						// 如果是奇数，放回队列，等待消费者消费
						sharedQueue.produce(number);
					}
					Thread.sleep(50);  // 暂停一会，模拟消费过程
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

	// 奇数消费者
	static class OddConsumer implements Runnable {
		private final SharedQueue sharedQueue;

		public OddConsumer(SharedQueue sharedQueue) {
			this.sharedQueue = sharedQueue;
		}

		@Override
		public void run() {
			try {
				while (true) {
					int number = sharedQueue.consume();
					if (number % 2 != 0) {
						System.out.println("奇数消费者消费奇数数字: " + number);
					} else {
						// 如果是偶数，放回队列，等待消费者消费
						sharedQueue.produce(number);
					}
					Thread.sleep(50);  // 暂停一会，模拟消费过程
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

	public static void main(String[] args) {
		SharedQueue sharedQueue = new SharedQueue(10);  // 设置队列容量为10

		ExecutorService executorService = Executors.newFixedThreadPool(4);  // 4个线程，1个生产者 + 2个消费者

		executorService.submit(new Producer(sharedQueue));
		executorService.submit(new EvenConsumer(sharedQueue));
		executorService.submit(new OddConsumer(sharedQueue));

		// 程序运行一段时间后关闭线程池
		try {
			Thread.sleep(10000);  // 运行10秒后退出
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}

		executorService.shutdownNow();
	}
}

